﻿/*
 * Copyright © 2025−2026 WEI.ZHOU (Willis) (Chengdu). All rights reserved.
 *
 * THIS SOURCE CODE IS PROPRIETARY AND CONFIDENTIAL.
 * It is the exclusive property of WEI.ZHOU (Willis) and may not be
 * used, copied, distributed, or disclosed outside of WEI.ZHOU (Willis)
 * without express written permission.
 *
 * This code is provided to WEI.ZHOU (Willis) under a limited,
 * non-transferable internal license, and is for use only with the author's
 * approved purposes. No external license is granted or implied.
 *
 * Any unauthorized use, reproduction, or distribution is strictly prohibited
 * and may result in severe civil and criminal penalties.
 */

using Aore.Core.Factorys.DbConnection;
using Aore.Core.Repository.Dapper;
using Aore.Core.Repository.EFCore;
using Autofac;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NLog;
using System.Reflection;

namespace Aore.Core.Extensions;

public static class AtuofacConfigExtensions
{
  public static void AddModule(this IServiceCollection services, ContainerBuilder builder, IConfiguration configuration)
  {
    // 规则：
    // 1. 扫描 YourProject.Data 程序集
    // 2. 找出所有以 "Repository" 结尾的类
    // 3. 确保它们是公共的、非抽象的类
    // 4. 将它们注册为其实现的所有接口 (AsImplementedInterfaces())
    // 5. 设置生命周期为 Scoped
    builder.RegisterAssemblyTypes(Assembly.Load("Aore.Repository")) // 或者 Assembly.GetExecutingAssembly() 如果这个模块在 Data 项目中
      .Where(t => t.Name.EndsWith("Repository") && t.IsPublic && !t.IsAbstract)
      .AsImplementedInterfaces()
      .InstancePerLifetimeScope();
    
    builder.RegisterAssemblyTypes(Assembly.Load("Aore.Service")) // 或者 Assembly.GetExecutingAssembly() 如果这个模块在 Data 项目中
      .Where(t => t.Name.EndsWith("Service") && t.IsPublic && !t.IsAbstract)
      .AsImplementedInterfaces()
      .InstancePerLifetimeScope();

    builder.Register<Func<Type, NLog.ILogger>>(c => (type) => LogManager.GetLogger(type.FullName))
      .SingleInstance();

    // EF Core DbContext 单例（整个应用程序生命周期内单例）
    builder.RegisterType<ApplicationDbContext>().SingleInstance();

    // EF Core 注册泛型仓储
    builder.RegisterGeneric(typeof(EfRepository<>))
      .As(typeof(IEfRepository<>))
      .InstancePerLifetimeScope();
    
    // 注册DapperRepository需要的Factory
    builder.RegisterType<DatabaseConnectionFactory>().As<IDbConnectionFactory>();
    
    // 注册DapperRepository
    builder.RegisterGeneric(typeof(DbRepository<>))
      .As(typeof(IDbRepository<>))
      .InstancePerLifetimeScope();

    //builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

    // 同时保留一个默认logger（可选）
    /*builder.RegisterInstance(LogManager.GetCurrentClassLogger())
      .As<NLog.ILogger>()
      .SingleInstance()
      .PreserveExistingDefaults();*/
  }
}